package com.pcbly.web.business.form;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pcbly.web.bean.field.FormTableDataBean;
import com.pcbly.web.bean.field.FormTypeBean;
import com.pcbly.web.bean.table.ColumnBean;
import com.pcbly.web.bean.table.TableBean;
import com.pcbly.web.business.BaseServiceImp;
import com.pcbly.web.components.form.AnalyseHtml;
import com.pcbly.web.components.utils.LightsoftStringUtils;
import com.pcbly.web.persistence.form.FormTableDataDao;
import com.pcbly.web.persistence.form.FormTypeDao;
import com.pcbly.web.persistence.table.ColumnDao;
import com.pcbly.web.persistence.table.TableDao;

public class FormTypeServiceImp extends BaseServiceImp<FormTypeBean> implements
		FormTypeService {

	protected static final Log logger = LogFactory
			.getLog(FormTypeServiceImp.class);
	
	private FormTypeDao formTypeDao;
	
	private FormTableDataDao formTableDataDao;
	
	private ColumnDao columnDao;
	
	private TableDao tableDao;
	
	private MacroComponentService macroComponentService;

	public void setFormTableDataDao(FormTableDataDao formTableDataDao) {
		this.formTableDataDao = formTableDataDao;
	}

	public void setColumnDao(ColumnDao columnDao) {
		this.columnDao = columnDao;
	}

	public void setTableDao(TableDao tableDao) {
		this.tableDao = tableDao;
	}

	public FormTypeServiceImp() {
		super();
	}

	public void setFormTypeDao(FormTypeDao formTypeDao) {
		this.formTypeDao = formTypeDao;
	}

	public List<FormTypeBean> findFormTypeBeansBySortId(String formSortId)
			throws Exception {
		// TODO Auto-generated method stub
		return formTypeDao.findFormTypeBeansBySortId(formSortId);
	}

	@Override
	public FormTypeBean findFormTypeBeanById(String Id) throws Exception {
		// TODO Auto-generated method stub
		return formTypeDao.findFormTypeBeanById(Id);
	}

	public void saveFormType(FormTypeBean bean) throws Exception {
		formTypeDao.saveFormType(bean);
	}

	protected StringBuilder fillKeyValue(String dataId, String id) {
		StringBuilder sb = new StringBuilder();
		sb.append("<input type=\"hidden\" id=\"dataId");
		sb.append("\" name=\"dataId");
		sb.append("\" value=\"");
		sb.append(dataId);
		sb.append("\" tableName=\"t_form_table_data");
		sb.append("\" columnName=\"ID");
		sb.append("\" dataLength=\"63");
		sb.append("\" dataType=\"varchar\" value=\"");
		sb.append("\"/>");
		sb.append("<input type=\"hidden\" id=\"fortId");
		sb.append("\" name=\"fortId");
		sb.append("\" tableName=\"t_form_table_data");
		sb.append("\" columnName=\"FORMID");
		sb.append("\" dataLength=\"63");
		sb.append("\" dataType=\"varchar\" value=\"");
		sb.append(id);
		sb.append("\"/>");

		return sb;
	}

	protected StringBuilder fillTableKeyValue(
			List<FormTableDataBean> tableDataBeans, String[] tableIdTSplit,
			List<TableBean> tableBeans) {
		StringBuilder sb = new StringBuilder();
		for (String tableIdTSplits : tableIdTSplit) {// 增加关键字
			for (TableBean tableBean : tableBeans) {
				if (tableIdTSplits.equals(tableBean.getId())) {
					String value = "";
					if (!tableDataBeans.isEmpty()) {
						for (FormTableDataBean tableDataBean : tableDataBeans) {
							if (tableIdTSplits.equals(tableDataBean
									.getTableId())) {
								value = tableDataBean.getKeyId();
								break;
							}
						}
					}
					sb.append("<input type=\"hidden\" id=\"id_");
					sb.append(tableIdTSplits);
					sb.append("\" name=\"id_");
					sb.append(tableIdTSplits);
					sb.append("\" value=\"");
					sb.append(value);
					sb.append("\" table=\"");
					sb.append(tableIdTSplits);
					sb.append("\" tableName=\"");
					sb.append(tableBean.getTableName());
					sb.append("\" dataLength=\"63");
					sb.append("\" dataType=\"varchar");
					sb.append("\" columnName=\"ID");
					sb.append("\"/>");
					break;
				}
			}

		}
		return sb;
	}

	public StringBuilder getStringBByFormTypeId(String id, String dataId)
			throws Exception {
		
		StringBuilder sb = new StringBuilder();
		try{
		FormTypeBean bean = formTypeDao.findFormTypeBeanById(id);
		String data = bean.getPrintModel();
		/** ******query data from database******** */
		List<FormTableDataBean> tableDataBeans = new ArrayList<FormTableDataBean>();
		tableDataBeans = formTableDataDao.queryFormTableDataBeansByFormIdAndId(
				id, dataId);
//		data = data.replaceAll("\r", " ").replaceAll("\n", " ").replaceAll(
//				"\n\r", " ").replaceAll("\r\n", " ");
		// System.out.println(data);
		List<String> tableIds = LightsoftStringUtils.patternRegStringToArray(
				data, "table=(\"[^\"]*\")");
		String tableIdT = "";
		for (String tableId : tableIds) {
			if (!(tableIdT.indexOf(tableId) >= 0)) {
				tableIdT = tableIdT + tableId + ",";
			}
		}
		// set default css if this have css.
		if (!(bean.getUserCss() == null || "".equals(bean.getUserCss()))) {
			sb.append("<style type=\"text/css\">");
			sb.append(bean.getUserCss());
			sb.append("</style>");
		}
		// set default javascript if this have javascript.
		if (!(bean.getUserScript() == null || "".equals(bean.getUserScript()))) {
			sb.append("<script type=\"text/javascript\">");
			sb.append(bean.getUserScript());
			sb.append("</script>");
		}
		// set default form name if this have form name.
		if (!(bean.getFormName() == null || "".equals(bean.getFormName()))) {
			sb.append("<center><h2><b>");
			sb.append(bean.getFormName());
			sb.append("</b></h2></center>");
		}
		// check table
		if (tableIdT.length() > 1)
			tableIdT = tableIdT.substring(0, tableIdT.length() - 1);
		String[] tableIdTSplit = tableIdT.split(",");

		if (tableIdTSplit.length >= 1) {// check not less than one table
			List<String> columnIds = LightsoftStringUtils
					.patternRegStringToArray(data, "name=(\"[^\"]*\")");
			List<TableBean> tableBeans = tableDao
					.findTableBeansByTableIds(tableIdT);
			data = analyseHtml(data, tableIds, columnIds, tableIdT, tableBeans,
					tableDataBeans);

			// fill tables key value
			sb.append(fillTableKeyValue(tableDataBeans, tableIdTSplit,
					tableBeans));

			// fill key value
			sb.append(fillKeyValue(dataId, id));

			sb.append(data);
		} else {
			sb.append(data);
			throw new Exception("读取" + id + "出现问题！请确认是来自与表单设计。");
		}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return sb;
	}

	protected String analyseHtml(String content, List<String> tableIds,
			List<String> columnIds, String tableIdT,
			List<TableBean> tableBeans, List<FormTableDataBean> tableDataBeans)
			throws Exception {
		AnalyseHtml html = new AnalyseHtml();
		html.setElement(content);

		html.setTableDataBeans(tableDataBeans);
		List<HashMap<String, HashMap<String, String>>> tableDatas = new ArrayList<HashMap<String, HashMap<String, String>>>();
		for (TableBean tableBean : tableBeans) {// fill data
			for (FormTableDataBean tableDataBean : tableDataBeans) {
				if (tableDataBean.getTableId().equals(tableBean.getId())) {
					HashMap<String, HashMap<String, String>> map = new HashMap<String, HashMap<String, String>>();
					map.put(tableBean.getId(), macroComponentService
							.findDataByTabelNameAndId(tableBean.getTableName(),
									tableDataBean.getKeyId()));
					tableDatas.add(map);
				}
			}
		}
		html.setTableDatas(tableDatas);

		html.setMacroComponentService(macroComponentService);
		List<String> idtandclist = new ArrayList<String>();
		List<String> tandclist = new ArrayList<String>();

		List<ColumnBean> columnBeans = columnDao
				.findColumnBeansBytableIds(tableIdT);

		for (int i = 0; i < tableIds.size(); i++) {
			String t = tableIds.get(i);
			String c = columnIds.get(i);
			for (ColumnBean columnBean : columnBeans) {
				if ((c.indexOf(columnBean.getId()) >= 0)
						&& t.indexOf(columnBean.getTableBean().getId()) >= 0) {
					StringBuilder replace = new StringBuilder();
					replace.append(columnBean.getColumnName());
					replace.append("_");
					replace.append(t);
					replace.append("_");
					replace.append(c);
					tandclist.add(replace.toString());
					idtandclist.add("id_" + t + "_" + c);
					break;
				}
			}
		}
		html.setIdtandclist(idtandclist);
		html.setTandclist(tandclist);
		html.setColumnBeans(columnBeans);
		html.setTableBeans(tableBeans);

		content = html.getHtml();
		return content;
	}

	@Override
	public void updateFormType(FormTypeBean bean) throws Exception {
		// TODO Auto-generated method stub
		formTypeDao.updateFormType(bean);
	}

	@Override
	public void deleteFormType(String id) throws Exception {
		// TODO Auto-generated method stub
		formTypeDao.removeById(FormTypeBean.class, id);
	}

	public void setMacroComponentService(
			MacroComponentService macroComponentService) {
		this.macroComponentService = macroComponentService;
	}

	@Override
	public String dwrSave(String data, String formId) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
